/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.ifrn.Dao;

import br.edu.ifrn.Classes.Conexao;
import br.edu.ifrn.Classes.Curso;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Edmilson
 */
public class CursoDao {

    private Connection connection;

    public CursoDao() {
        this.connection = new Conexao().getConnection();
    }

    public void InserirCurso(Curso curso) {
        String sql = "insert into curso" + "(id, nome, descricao)"
                + "values(?,?,?)";

        try {
            PreparedStatement stmt = connection.prepareStatement(sql);

            stmt.setInt(1, curso.getId());
            stmt.setString(2, curso.getNome());
            stmt.setString(3, curso.getDescricao());
            stmt.execute();
            stmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void remove(Curso curso) {
        try {
            PreparedStatement stmt = connection.prepareStatement("delete from Curso where id=?");
            stmt.setInt(1, curso.getId());
            stmt.execute();
            stmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    
    public void editarCurso(Curso curso){
        String sql = "UPDATE Curso SET nome=?, descricao=? WHERE id=?";
        
        try{
            java.sql.PreparedStatement stmt = this.connection.prepareStatement(sql);
            stmt.setString(1, curso.getNome());
            stmt.setString(2, curso.getDescricao());
            stmt.setInt(3, curso.getId());
            
            stmt.execute();
            stmt.close();
        }catch(SQLException e){
            throw new RuntimeException(e);            
        }
    }

    public List<Curso> getLista() {
        try {
            List<Curso> cursos = new ArrayList<Curso>();
            PreparedStatement stmt = this.connection.prepareStatement("select * from curso");
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                // criando o objeto Contato
                Curso curso = new Curso();
                curso.setId(rs.getInt("id"));
                curso.setNome(rs.getString("nome"));
                curso.setDescricao(rs.getString("descricao"));

                // adicionando o objeto à lista
                cursos.add(curso);
            }
            rs.close();
            stmt.close();
            return cursos;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
